/*
 * @Author: DUST
 * @Date: 2023-05-26 16:52:07
 * @LastEditors: DUST
 * @LastEditTime: 2023-11-26 11:03:19
 * @FilePath: \business-card-system\server\app\controller\LoginController.ts
 * @Description:
 * undefined
 */
import { Context } from "koa";
import { sign } from "../../utils/auth";
import responseData from "../../utils/responese";
import validate from "../../utils/validator";
import LoginValidator, { LoginParams } from "../validator/LoginValidator";
import AccountService from "../service/AccountService";
import MD5 from "../../utils/MD5";

class LoginController {
  /**
   * @description: 用户登录
   * @param {Context} ctx：请求体
   */
  async doLogin(ctx: Context) {
    // 参数校验
    const { data, msg } = await validate<LoginParams>(
      ctx,
      LoginValidator.loginRules
    );
    if (msg !== null) return responseData.errorResponese(ctx, msg);
    // 根据用户名查询账号
    const account = await AccountService.getAccountByUsername(data.username);
    console.log(MD5(data.password));
    if (account === null)
      return responseData.errorResponese(ctx, "未查询到账号！");
    else if (MD5(data.password) != account.getDataValue("password"))
      return responseData.errorResponese(ctx, "密码错误！");
    // 根据账号信息生成token
    const timeStamp = Date.now();
    const token = sign({ ...account, timeStamp });

    responseData.success(ctx, {
      token,
      timeStamp,
      id: account.getDataValue("id"),
      unitId: account.getDataValue("unitId"),
      adminType: account.getDataValue("adminType"),
      actionPower: account.getDataValue("actionPower"),
      menuPower: account.getDataValue("menuPower"),
    });
  }
  /**
   * @description: 获取用户信息
   * @param {Context} ctx:请求体
   */
  async getUserInfo(ctx: Context) {
    const params = ctx.params;
    if (isNaN(params.id))
      return responseData.errorResponese(ctx, "参数错误！");
    console.log(params);

    const userinfo = await AccountService.getUserInfoById(params.id);

    if (userinfo === null)
      return responseData.errorResponese(ctx, "未查询到信息");
    console.log(userinfo)
    responseData.success(ctx, userinfo);
  }

  public changePwd = async (ctx: Context) => {
    const {
      data: { pwd, pwd1, pwd2, id },
      msg,
    } = await validate<{ pwd: string; pwd1: string; pwd2: string; } & { id: number }>(
      ctx,
      LoginValidator.editRules
    );
    const userinfo = await AccountService.getUserInfoById(id);
    if(userinfo) {
      if(userinfo.password != MD5(pwd)) return responseData.errorResponese(ctx, "原密码错误！");
      if(pwd1 !== pwd2) return responseData.errorResponese(ctx, "两次输入的密码不一致！");
      const row = await AccountService.editUserPwd({ password: MD5(pwd1) }, id);
      if(row) return responseData.success(ctx, null, "密码修改成功");
      return responseData.success(ctx, null, "密码修改失败！");
    }
    
    return responseData.errorResponese(ctx, "未知错误");
  }
}

export default new LoginController();
